package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.util.JwtUtils;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties prop;

    public void login(String username, String password, HttpServletResponse response) {
        // 	1.利用用户名密码，去ly-user查询用户（验证用户密码是否正确）
        UserDTO userDTO = null;
        try {
            userDTO = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (Exception e) {
            // 用户查询失败
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD, e);
        }

        //	2.如果正确，利用私钥生成JWT
        UserInfo userInfo = new UserInfo(userDTO.getId(), userDTO.getUsername(), "guest");
        String token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), UserTokenConstants.EXPIRE_MINUTES);

        //	3.把JWT写到用户cookie  response
        writeTokenInCookie(response, token);
    }

    private void writeTokenInCookie(HttpServletResponse response, String token) {
        CookieUtils.newCookieBuilder()
                .name(UserTokenConstants.COOKIE_NAME).value(token)
                .httpOnly(true)
                .domain(UserTokenConstants.DOMAIN)
                .response(response)
                .build();
    }

    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        //  1.获取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        //	2.验证并解析token
        Payload<UserInfo> payload = null;
        try {
            // 2.1.有效性校验
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 解析失败，无效token或token过期，未登录或登录过期
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        // 2.2.黑名单校验
        Boolean isExists = redisTemplate.hasKey(payload.getId());
        if(BooleanUtils.isTrue(isExists)){
            // 黑名单存在，token无效
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
        //	3.判断用户身份，返回用户信息
        UserInfo userInfo = payload.getUserInfo();

        // 4.刷新token
        // 4.1.获取cookie中的剩余时间
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 4.2.判断是否触发刷新的阈值
        if(remainTime < UserTokenConstants.REFRESH_REMAIN_TIME_THRESHOLD) {
            // 4.3.如果触发，重新生成token
            token = JwtUtils.generateTokenExpireInMinutes(userInfo, prop.getPrivateKey(), UserTokenConstants.EXPIRE_MINUTES);
            // 4.4.覆盖cookie
            writeTokenInCookie(response, token);
        }
        return userInfo;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //  1.获取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        //	2.验证并解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 解析失败，无效token或token过期，未登录或登录过期
            return;
        }
        // 3.删除cookie
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME, UserTokenConstants.DOMAIN, response);

        // 4.记录token的id到redis（记录黑名单）
        // 4.1.获取token的剩余有效期
        long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
        // 4.2.写入redis，设置过期时间
        redisTemplate.opsForValue().set(payload.getId(), "1", remainTime, TimeUnit.MILLISECONDS);
    }
}
